<template>
	<div class="container">
		<h2 style="text-align: center;margin-bottom: 30px;">采购单</h2>
		<a-descriptions title="采购单信息" style="margin-bottom: 20px;">
			<a-col :span="24" label="项目名称">
				<a-descriptions-item>{{ formState.project?.name }}</a-descriptions-item>
			</a-col>
			<a-descriptions-item label="采购编号">{{ purchaseOrderInfo.code }}</a-descriptions-item>
			<a-descriptions-item label="创建时间">{{ purchaseOrderInfo.create_time }}</a-descriptions-item>
			<a-descriptions-item label="送达地址">{{ formState.deliver_address }}</a-descriptions-item>
			<a-descriptions-item label="送达时间">{{ formState.deliver_time }}</a-descriptions-item>
			<a-descriptions-item label="联系人">{{ formState.receiver }}</a-descriptions-item>
			<a-descriptions-item label="联系电话">{{ formState.receiver_tel }}</a-descriptions-item>
		</a-descriptions>
		<a-form ref="formRef" :model="formState" @finish="handleSave">
			<a-row :gutter="20">
				<a-col :span="24">
					<h1 style="margin-top: 30px;">本次采购物资清单</h1>
					<a-table v-if="type === 'purchase'" :pagination="false" :data-source="formState.materials" :columns="purchaseColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ text, record, column, index }">
							<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
							<template v-else-if="column.dataIndex === 'real_quantity'">
								<a-form-item :name="['materials', index, 'real_quantity']">
									<a-input-number v-model:value="formState.materials[index].real_quantity" style="width: 100%" placeholder="请输入数量" @blur="remainder(text, record, index)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'remainder'">
								<h1>{{ record.remainder }}</h1>
							</template>
						</template>
					</a-table>
					<a-col v-if="type === 'machineapply'">
						<a-table :pagination="false" :data-source="formState.materials" :columns="machineapplyColumns" :row-key="(record) => record.key">
							<template #bodyCell="{ column, index }">
								<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
								<template v-else-if="column.dataIndex === 'real_quantity'">
									<a-form-item :name="['materials', index, 'real_quantity']">
										<a-input-number v-model:value="formState.materials[index].real_quantity" style="width: 100%" placeholder="请输入数量" @change="checkQuantity(formState.materials[index].real_quantity, formState.materials[index])" />
									</a-form-item>
								</template>
							</template>
						</a-table>
					</a-col>
					<a-col v-if="type === 'shangtong'">
						<a-table :pagination="false" :data-source="formState.materials" :columns="shangtongColumns" :row-key="(record) => record.key">
							<template #bodyCell="{ column, index, record }">
								<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
								<template v-else-if="column.dataIndex === 'art_indexes'">
									<span v-for="(item, ii) in record.art_indexes" :key="ii" class="mr-5">
										{{ artIndexesGongHaos.find(i => i.value === item.gonghao_id)?.label }};
									</span>
								</template>
								<template v-else-if="column.dataIndex === 'real_quantity'">
									<a-form-item :name="['materials', index, 'real_quantity']" @change="checkRealQuantity(formState.materials[index].real_quantity, formState.materials[index])">
										<a-input-number v-model:value="formState.materials[index].real_quantity" style="width: 100%" placeholder="请输入" />
									</a-form-item>
								</template>
							</template>
						</a-table>
					</a-col>
					<a-table v-if="type === 'auxiliary'" :pagination="false" :data-source="formState.materials" :columns="auxiliaryColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ text, record, column, index }">
							<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
							<template v-else-if="column.dataIndex === 'real_quantity'">
								<a-form-item :name="['materials', index, 'real_quantity']">
									<a-input-number v-model:value="formState.materials[index].real_quantity" style="width: 100%" placeholder="请输入数量" @blur="remainder(text, record, index)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'remainder'">
								<h1>{{ record.remainder }}</h1>
							</template>
						</template>
					</a-table>
					<a-table v-if="type === 'a_few_employ'" :pagination="false" :data-source="formState.materials" :columns="auxiliaryColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ text, record, column, index }">
							<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
							<template v-else-if="column.dataIndex === 'real_quantity'">
								<a-form-item :name="['materials', index, 'real_quantity']">
									<a-input-number v-model:value="formState.materials[index].real_quantity" style="width: 100%" placeholder="请输入数量" @blur="remainder(text, record, index)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'remainder'">
								<h1>{{ record.remainder }}</h1>
							</template>
						</template>
					</a-table>
				</a-col>

				<!-- <a-col v-if="type === 'shangtong'">
					<h3>采购物资清单</h3>
					<a-form ref="formRef" style="width:100%" :model="formState">
						<div class="flex" style="flex-wrap: wrap;">
							<a-form-item style="width:50%" label="预计浇筑方量（m3）">
								{{ formState.materials[0].fangliang }}
							</a-form-item>
							<a-form-item style="width:50%" label="浇筑方量（m3）">
								<a-input v-model:value="formState.materials[0].real_quantity" placeholder="请输入" />
							</a-form-item>
							<a-form-item style="width:50%" label="是否泵送（长度）">
								{{ formState.materials[0].changdu }}
							</a-form-item>
							<a-form-item style="width:50%" label="申请塌落度（mm）">
								{{ formState.materials[0].luodu }}
							</a-form-item>
							<a-form-item style="width:50%" label="预计浇筑日期">
								{{ formState.materials[0].add_time }}
							</a-form-item>
						</div>
						
					</a-form>
				</a-col>-->

				<!-- <a-col :span="24" style="margin-top: 24px;">
					<a-form-item class="flex-auto" label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{minRows:4, maxRows:6}"></a-textarea>
					</a-form-item>
				</a-col>-->
			</a-row>
			<a-row :gutter="20">
				<a-col :span="8" class="py-4">
					<a-form-item label="发货附件" name="real_pic_path" :rules="{required:true, message:'请上传发货附件'}">
						<a-upload v-model:file-list="formState.real_pic_path" name="upload" :action="`${baseURL}/contract/upload`" accept=".jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx" :show-upload-list="true" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" :before-upload="picbeforeUpload" @change="picchangeUpload">
							<a-button>
								<template v-if="pic_uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传发货附件
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
			</a-row>
			<div v-if="shipSplitHistory.length">
				<h1 style="margin-top: 30px;">历史发货记录</h1>
				<a-collapse v-model:activeKey="activeKey">
					<a-collapse-panel v-for="(item, index) in shipSplitHistory" :key="index" :header="'发货单号：' + item.code">
						<h3 style="padding-left:10px;">物资清单</h3>
						<a-table :pagination="false" :data-source="item.materials" :columns="historyColumns" :row-key="(record) => record.key"></a-table>
						<h3 style="padding-left:10px;">发货附件</h3>
						<a-row v-if="item.realPicList?.length" :gutter="24">
							<a-col v-for="i in item.realPicList" :key="i.url" :span="6">
								<div class="gallery-image">
									<a-image :width="160" :height="160" :src="item.i" />
								</div>
								<p>{{ item.name }}</p>
							</a-col>
						</a-row>
					</a-collapse-panel>
				</a-collapse>
			</div>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button type="primary" html-type="submit">
							<save-outlined />确定发货
						</a-button>

						<a-button @click="closeTab('/supply/order')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup lang="jsx">
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { Modal } from "ant-design-vue";
import { DeleteOutlined, SaveOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { post, treeToList } from "../utils";
import { useRoute } from "vue-router";
import dayjs from "dayjs";
import { baseURL } from "../utils/request";

const remainder = (text, record) => {
	if (text) {
		if (record.quantity - text < 0) {
			Modal.confirm({
				title: "提示",
				content: '超出发货数量'
			})
			record.remainder = '0.00'
			record.real_quantity = null;
		} else {
			record.remainder = (record.quantity - text).toFixed(2)
		}

	}
}
const route = useRoute();
const formState = ref({ materials: [] });
const formRef = ref();
const { proxy } = getCurrentInstance();
const shipSplitHistory = ref([]);
const activeKey = ref([]);
const purchaseColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "订货数",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "本次发货余量",
		dataIndex: "remainder",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const machineapplyColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "机械名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center",
		width: 150
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "使用时长",
		dataIndex: "use_time",
		align: "center"
	},
	// {
	// 	title: "时长单位",
	// 	dataIndex: "time_unit",
	// 	align: "center"
	// },
	{
		title: "使用时间",
		dataIndex: "use_date",
		align: "center",
		width: 190,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const shangtongColumns = [
	{
		title: "工号",
		dataIndex: "use_position",
		ellipsis: true,
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		ellipsis: true,
	},
	{
		title: "砼标号（类别）",
		dataIndex: "model",
		customRender: ({ text, record, index, column }) => {
			return record.name + text;
		}
	},
	{
		title: "采购方量（m3）",
		dataIndex: "fangliang",
		align: "center"
	},
	{
		title: "浇筑方量（m3）",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		align: "center"
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		align: "center"
	},
	{
		title: "技术指标",
		dataIndex: "art_indexes",
		align: "center"
	},
	{
		title: "预计浇筑日期",
		dataIndex: "add_time",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const auxiliaryColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "订货数",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "发货数量",
		dataIndex: "real_quantity",
		align: "center"
	},
	{
		title: "本次发货余量",
		dataIndex: "remainder",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const historyColumns = computed(() => {
	if (type.value === 'shangtong') {
		return [{
			title: "工号",
			dataIndex: 'use_position',
			ellipsis: true
		},
		{
			title: "预计浇筑部位",
			dataIndex: "SupplyOrderMaterial",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text.expected_location;
			}
		},
		{
			title: "砼标号（类别）",
			dataIndex: "model",
			customRender: ({ text, record, index, column }) => {
				return record.name + text;
			}
		},
		{
			title: "采购方量（m3）",
			dataIndex: "SupplyOrderMaterial",
			customRender: ({ text, record, index, column }) => {
				return text.fangliang;
			}
		},
		{
			title: "浇筑方量（m3）",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.real_quantity;
			}
		}]
	}
	return [
		{
			title: "物资名称",
			dataIndex: "name",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "型号规格",
			dataIndex: "model",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "单位",
			dataIndex: "unit",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "采购数量",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.quantity;
			}
		},
		{
			title: "发货数量",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.real_quantity;
			}
		}
	]
})

// 物资信息
const purchaseOrderInfo = ref({});
const id = computed(() => route.params.id);
const type = ref();
const artIndexesGongHaos = ref([]);
const initInfo = () => {
	post(`supplyOrder/info`, { id: id.value }).then(async data => {
		type.value = data.purchaseOrder.type;
		if (type.value === 'shangtong') {
			post("dictionary", { root_id: 1069 }).then((data) => {
				artIndexesGongHaos.value = data.map(d => {
					return {
						value: d.id,
						label: d.name
					};
				});
			});
			const departmentTree = await post("department/getTrees", { type: 4, parent_id: data.project_id });
			const departmentList = treeToList(departmentTree, []);
			const info = data.materials[0]?.SupplyOrderMaterial || {}
			const gonghao = departmentList.filter((item) => {
				return item.id === info.gonghao_id
			})[0]?.name;
			const part = departmentList.filter((item) => {
				return item.id === info.position
			})[0]?.name;
			data.materials.map((item) => {
				item.use_position = ((gonghao || '') + (part || ''));
				return item;
			});
		}
		data.materials = data.materials.map(item => {
			const { quantity, unit, memo, use_date, use_time, time_unit, fangliang, luodu, changdu, add_time, part, expected_location, art_indexes } = item.SupplyOrderMaterial;
			return {
				...item,
				quantity,
				unit,
				memo,
				expected_location,
				use_date,
				use_time,
				time_unit,
				fangliang,
				luodu,
				changdu,
				part,
				add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss"),
				art_indexes: art_indexes ? JSON.parse(art_indexes) : [],
			};
		});
		const purchaseOrder = data.purchaseOrder;
		purchaseOrder.create_time = dayjs(purchaseOrder.create_time).format("YYYY-MM-DD HH:mm:ss");
		purchaseOrderInfo.value = purchaseOrder;
		formState.value = data
		if (formState.value.real_pic_path) {
			formState.value.real_pic_path = JSON.parse(formState.value.real_pic_path)
		}
		if (formState.value.deliver_time) {
			formState.value.deliver_time = dayjs(formState.value.deliver_time).format("YYYY-MM-DD HH:mm:ss");
		}
		formState.value.materials = formState.value.materials.map(item => ({ ...item, remainder: item.quantity }))
		shipSplitHistory.value = (await post("supplyOrder", { purchase_order_code: formState.value.purchase_order_code, ship_status: 2 })).data.filter(item => item.id !== parseInt(id.value));
		shipSplitHistory.value.map(item => {
			item.realPicList = JSON.parse(item.real_pic_path || "[]");
			return item;
		})
		if (type.value === 'shangtong' && shipSplitHistory.value.length) {
			const departmentTree = await post("department/getTrees", { type: 4, parent_id: data.project_id });
			const departmentList = treeToList(departmentTree, []);
			for (const item of shipSplitHistory.value) {
				const info = item.materials[0]?.SupplyOrderMaterial || {}
				const gonghao = departmentList.filter((item) => {
					return item.id === info.gonghao_id
				})[0]?.name;
				const part = departmentList.filter((item) => {
					return item.id === info.position
				})[0]?.name;
				item.materials.map((i) => {
					i.use_position = ((gonghao || '') + (part || ''));
					return i;
				});
			}
		}
	});
}
onMounted(() => {
	initInfo();
});

// 检验浇筑放量
function checkRealQuantity(real_quantity, material) {
	if (formState.value.ys_type === 2) {
		if (isNaN(parseFloat(real_quantity)) || parseFloat(real_quantity) > parseFloat(material.fangliang) * 1.2) {
			material.real_quantity = material.fangliang;
			proxy.$message.error("浇筑方量不能大于预计浇筑方量的百分之20");
		}
	} else {
		if (isNaN(parseFloat(real_quantity)) || parseFloat(real_quantity) > parseFloat(material.fangliang)) {
			material.real_quantity = material.fangliang;
			proxy.$message.error("浇筑方量不能大于预计浇筑方量");
		}
	}

}
// 检查数量
function checkQuantity(quantity, material) {
	if (isNaN(parseFloat(quantity)) || parseFloat(quantity) > parseFloat(material.quantity)) {
		material.real_quantity = material.quantity;
		proxy.$message.error("订货数不能大于采购数量");
	}
}
const pic_uploading = ref(false);
const picbeforeUpload = file => {
	pic_uploading.value = true;
};
// 上传并提交文件
const picchangeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.real_pic_path.push({
			name: file.name,
			url: file.response.data.url
		})
		pic_uploading.value = false;
		formState.value.real_pic_path = formState.value.real_pic_path.filter((item) => item.url)
		proxy.$message.success("发货图片上传成功");
	}
	if (!file.status) {
		formState.value.real_pic_path = formState.value.real_pic_path.filter((item) => item.url)
	}
};
const handleSave = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			let ship_split = 0;
			const materials = formState.value.materials.map(item => {
				if ((item.real_quantity || 0) < (item.quantity || item.fangliang)) {
					ship_split = 1;
				}
				return {
					id: item.SupplyOrderMaterial.id,
					real_quantity: item.real_quantity || 0,
				};
			});
			if (!materials.filter((item) => item.real_quantity > 0).length) {
				return proxy.$message.error('请至少操作一个物料发货');
			}
			ship_split = formState.value.ship_split === 1 ? 0 : ship_split;
			const params = {
				materials: JSON.stringify(materials),
				id: id.value,
				opr_type: "fahuo",
				real_pic_path: JSON.stringify(formState.value.real_pic_path),
				ship_split,
			};
			Modal.confirm({
				title: "操作确认?",
				content: ship_split === 1 ? "您确定要拆单发货吗，请确认" : '您确定要发货吗，请确认',
				onOk() {
					post("supplyOrder/save", params)
						.then(() => {
							proxy.$message.success("发货成功", 1);
							if (ship_split) {
								initInfo()
							} else {
								closeTab("/supply/order");
							}

						})
						.catch(err => {
							proxy.$message.error(err);
						});
				}
			});
		})
		.catch(err => {
			proxy.$message.error(err.message);
		});
};

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;

	:deep(.ant-table-cell) .ant-form-item {
		margin-bottom: 0;

		.ant-form-item-explain {
			position: absolute;
			bottom: -24px;
		}
	}
	:deep(.ant-collapse-content-box) {
		padding: 0px;
	}
}
</style>
